<template>
  <div class="coupon">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="searchData" size="medium" label-width="100px">
        <el-col :span="12">
          <el-form-item label="优惠券标题" prop="title">
            <el-input v-model="searchData.title" placeholder="请输入优惠券标题" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型" prop="kind">
            <el-select v-model="searchData.type" placeholder="请选择类型" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用场景" prop="used">
            <el-select v-model="searchData.used" placeholder="请选择适用场景" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in usedOptions" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-table
      :data="dataList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      v-show="dataList.length > 0"
    >
      <el-table-column label="标题" prop="title" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="场景" prop="used" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.used | used }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="icon" align="center" width="150">
        <template slot-scope="{ row }">
          <img v-if="row.icon" :src="row.icon" class="avatar"/>
        </template>
      </el-table-column>
      <el-table-column label="类别" prop="type" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.type | type}}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用条件" prop="withAmount" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.withAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用券金额" prop="usedAmount" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.usedAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配额" prop="quota" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.quota }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发放开始时间" prop="startTime" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发放结束时间" prop="endTime" align="center" width="100">
        <template slot-scope="{ row }">
          <span>{{ row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时效" prop="validType" align="center" width="160">
        <template slot-scope="{ row }">
          <!--<span>{{ row | validType }}</span>-->
          <span v-html="$options.filters.validType(row)"></span>
        </template>
      </el-table-column>
      <el-table-column label="领取需要的积分" prop="points" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.points }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券状态" prop="status" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.status | status }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" prop="id" align="center" width="200">
        <template slot-scope="{ row }">
          <el-button type="primary" @click="edit(row)">编辑</el-button>
          <el-button type="info" v-if="row.status === 1" @click="lock(row)">锁定</el-button>
          <el-button type="primary" v-else-if="row.status === 2" @click="lock(row)">启用</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="searchData.totalCount > 0"
                :total="searchData.totalCount"
                :page.sync="searchData.page"
                :limit.sync="searchData.pageSize"
                @pagination="search"
    />

    <el-dialog :title="title" class="dialogAdd" :visible.sync="dialogCouponVisible" top="30px" @open="onOpen"
               @close="onClose">
      <el-form ref="elForm" :model="addData" :rules="addRules" size="medium" label-width="100px">
        <el-form-item label="优惠券标题" prop="title">
          <el-input v-model="addData.title" placeholder="请输入优惠券标题" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <!--<el-form-item label="优惠券图片" prop="icon" required>
          <el-upload ref="icon" :file-list="iconfileList" :action="iconAction"
                     :before-upload="iconBeforeUpload">
            <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
          </el-upload>
        </el-form-item>-->

        <el-form-item label="优惠券图片">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="action"
            :drag="true"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="addData.icon" :src="addData.icon" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"/>
          </el-upload>
        </el-form-item>

        <el-form-item label="适用场景" prop="used">
          <el-select v-model="addData.used" placeholder="请选择适用场景" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in usedOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="type">
          <el-select v-model="addData.type" placeholder="请选择类别" clearable :style="{width: '100%'}">
            <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label"
                       :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="135px" label="特价商品可否使用" prop="withSpecial" required>
          <el-switch v-model="addData.withSpecial"></el-switch>
        </el-form-item>
        <el-form-item label-width="135px" label="优惠商品产品编号" prop="withSn" v-if="addData.withSpecial">
          <!--<el-input v-model="searchData.withSn" placeholder="请输入优惠商品产品编号" clearable :style="{width: '100%'}">
          </el-input>-->
          <el-autocomplete
            v-model="searchData.name"
            :fetch-suggestions="getNameData"
            placeholder="请输入优惠商品名称"
            @select="getChoose"
            clearable
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="使用条件" prop="withAmount">
          <el-input v-model="addData.withAmount" placeholder="满多少金额生效,默认0元" clearable
                    :style="{width: '100%'}">
            <template slot="prepend">￥</template>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="用券金额" prop="usedAmount" v-if="this.addData.type !== 4">
          <el-input v-model="addData.usedAmount" placeholder="请输入用券金额" clearable :style="{width: '100%'}">
            <template slot="prepend">￥</template>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="折扣" prop="usedAmountDiscount" v-if="this.addData.type === 4">
          <el-input v-model="addData.usedAmountDiscount" placeholder="请输入折扣,69折输入69" clearable
                    :style="{width: '100%'}">
            <template slot="append">%</template>
          </el-input>
        </el-form-item>
        <el-form-item label="配额" prop="quota">
          <el-input-number v-model="addData.quota" placeholder="配额" :step='1'></el-input-number>
        </el-form-item>
        <el-form-item label-width="120px" label="发放开始时间" prop="startTime">
          <el-date-picker type="datetime" v-model="addData.startTime" format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择发放开始时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label-width="120px" label="发放结束时间" prop="endTime">
          <el-date-picker type="datetime" v-model="addData.endTime" format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择发放结束时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时效" prop="validType">
          <el-radio-group v-model="addData.validType" size="medium">
            <el-radio v-for="(item, index) in validTypeOptions" :key="index" :label="item.value"
                      :disabled="item.disabled">{{item.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="120px" label="使用开始时间" prop="validStartTime" v-if="this.addData.validType === 1">
          <el-date-picker type="datetime" v-model="addData.validStartTime" format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择使用开始时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label-width="120px" label="使用结束时间" prop="validEndTime" v-if="this.addData.validType === 1">
          <el-date-picker type="datetime" v-model="addData.validEndTime" format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" placeholder="请选择使用结束时间" clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label-width="165px" label="自领取之日起有效天数" prop="validDays" v-if="this.addData.validType === 2">
          <el-input v-model="addData.validDays" placeholder="请输入自领取之日起有效天数" clearable
                    :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label-width="120px" label="领取需要的积分" prop="points">
          <el-input v-model="addData.points" placeholder="请输入领取需要的积分" clearable :style="{width: '100%'}">
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" prop="status">
          <el-radio-group v-model="addData.status" size="medium">
            <el-radio v-for="(item, index) in statusOptions" :key="index" :label="item.value"
                      :disabled="item.disabled">{{item.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {coupons, editCoupon} from '@/api/coupon'
  import {getProducts} from '@/api/product'
  import Pagination from "@/components/Pagination";

  let _that;

  export default {
    name: "couponManager",
    components: {Pagination},
    inheritAttrs: false,
    props: [],
    data() {
      return {
        title: "新增优惠券",
        dialogCouponVisible: false,
        action: "",

        dataList: [],

        searchData: {
          totalCount: 0,
          totalPage: 1,
          pageSize: 10
        },

        addData: {
          title: undefined,
          icon: null,
          used: undefined,
          type: undefined,
          withSpecial: false,
          withSn: undefined,
          withAmount: "",
          usedAmount: undefined,
          usedAmountDiscount: undefined,
          quota: 100,
          startTime: null,
          endTime: null,
          validType: 1,
          validStartTime: null,
          validEndTime: null,
          validDays: undefined,
          points: "",
          status: 1,
        },
        addRules: {
          title: [{
            required: true,
            message: '请输入优惠券标题',
            trigger: 'blur'
          }],
          used: [{
            required: true,
            message: '请选择适用场景',
            trigger: 'change'
          }],
          type: [{
            required: true,
            message: '请选择类别',
            trigger: 'change'
          }],
          withSn: [],
          withAmount: [{
            required: true,
            message: '满多少金额生效,默认0元',
            trigger: 'blur'
          }],
          usedAmount: [{
            required: true,
            message: '请输入用券金额',
            trigger: 'blur'
          }],
          usedAmountDiscount: [{
            required: true,
            message: '请输入折扣,69折输入69',
            trigger: 'blur'
          }],
          quota: [{
            required: true,
            message: '配额',
            trigger: 'blur'
          }],
          startTime: [{
            required: true,
            message: '请选择发放开始时间',
            trigger: 'change'
          }],
          endTime: [{
            required: true,
            message: '请选择发放结束时间',
            trigger: 'change'
          }],
          validType: [{
            required: true,
            message: '时效不能为空',
            trigger: 'change'
          }],
          validStartTime: [{
            required: true,
            message: '请选择使用开始时间',
            trigger: 'change'
          }],
          validEndTime: [{
            required: true,
            message: '请选择使用结束时间',
            trigger: 'change'
          }],
          validDays: [{
            required: true,
            message: '请输入自领取之日起有效天数',
            trigger: 'blur'
          }],
          points: [{
            required: true,
            message: '请输入领取需要的积分',
            trigger: 'blur'
          }],
          status: [{
            required: true,
            message: '优惠券状态不能为空',
            trigger: 'change'
          }],
        },
        iconAction: 'https://jsonplaceholder.typicode.com/posts/',
        iconfileList: [],
        usedOptions: [{
          "label": "门诊优惠券",
          "value": 10
        }, {
          "label": "新人门诊券 ",
          "value": 11
        }, {
          "label": " 商品优惠券  ",
          "value": 20
        }, {
          "label": "类目优惠券  ",
          "value": 30
        }, /*{
          "label": "平台优惠券 ",
          "value": 60
        }, {
          "label": "新人平台券",
          "value": 61
        }*/],
        typeOptions: [{
          "label": "满减券 ",
          "value": 1
        }, {
          "label": "叠加满减券",
          "value": 2
        }, {
          "label": " 无门槛券",
          "value": 3
        }, {
          "label": "折扣券",
          "value": 4
        }],
        validTypeOptions: [{
          "label": "绝对时效（领取后XXX-XXX时间段有效）",
          "value": 1
        }, {
          "label": "相对时效（领取后N天有效）",
          "value": 2
        }],
        statusOptions: [{
          "label": "生效",
          "value": 1
        }, {
          "label": "失效",
          "value": 2
        }, {
          "label": "已结束",
          "value": 3
        }],
      }
    },
    beforeCreate: function () {
      _that = this;
    },
    filters: {
      type(s) {
        let d = _that.typeOptions.filter(item => {
          return item.value === s;
        })
        return d[0].label
      },
      used(s) {
        let d = _that.usedOptions.filter(item => {
          return item.value === s;
        })
        return d[0].label
      },
      validType(row) {
        if (row.validType === 1) {
          return row.validStartTime + "<br/>|<br/>" + row.validEndTime
        }
        return row.validDays + "天有效"
      },
      status(s) {
        let d = _that.statusOptions.filter(item => {
          return item.value === s;
        })
        return d[0].label
      }
    },
    computed: {
      withSpecial() {
        return this.addData.withSpecial;
      },
      newName() {
        return this.addData.type;
      },
      validType() {
        return this.addData.validType;
      }
    },
    watch: {
      withSpecial(val) {
        if (this.addData.withSpecial) {
          this.addRules.withSn = [{
            required: true,
            message: '请输入商品编码',
            trigger: 'change'
          }];
        } else {
          this.addData.withSn = "";
          this.addRules.withSn = [{
            required: false,
            message: '请输入商品编码',
            trigger: 'blur'
          }];
        }
      },
      validType(val) {
        if (this.addData.validType === 1) {
          //绝对时效
          this.addRules.validStartTime = [{
            required: true,
            message: '请选择使用开始时间',
            trigger: 'change'
          }];
          this.addRules.validEndTime = [{
            required: true,
            message: '请选择使用结束时间',
            trigger: 'change'
          }];
          this.addRules.validDays = [{
            required: false,
            message: '请输入自领取之日起有效天数',
            trigger: 'blur'
          }];
          this.addData.validDays = "";
        } else {
          //相对时效
          this.addRules.validStartTime = [{
            required: false,
            message: '请选择使用开始时间',
            trigger: 'change'
          }];
          this.addRules.validEndTime = [{
            required: false,
            message: '请选择使用结束时间',
            trigger: 'change'
          }];
          this.addRules.validDays = [{
            required: true,
            message: '请输入自领取之日起有效天数',
            trigger: 'blur'
          }];
          this.addData.validStartTime = "";
          this.addData.validEndTime = "";
        }
      },
      newName(val) {
        this.value = val;
        if (this.addData.type === 4) {
          this.addRules.usedAmount = [{
            required: false,
            message: '请输入用券金额',
            trigger: 'blur'
          }];
          this.addRules.usedAmountDiscount = [{
            required: true,
            message: '请输入折扣,69折输入69',
            trigger: 'blur'
          }]
          this.addData.usedAmount = "";
        } else {
          this.addRules.usedAmount = [{
            required: true,
            message: '请输入用券金额',
            trigger: 'blur'
          }];
          this.addRules.usedAmountDiscount = [{
            required: false,
            message: '请输入折扣,69折输入69',
            trigger: 'blur'
          }];
          this.addData.usedAmountDiscount = "";
        }
      }
    },
    created() {
      this.action = process.env.VUE_APP_BASE_API + "/file/upload";
      this.search()
    },
    mounted() {
    },
    methods: {
      lock(row) {
        this.addData = row;
        this.addData.status = this.addData.status === 1 ? 2 : 1;
        this.handelConfirm();
      },
      edit(row) {
        this.addData = row;

        if (row.type === 4) {
          this.addData.usedAmountDiscount = row.usedAmount;
          this.addRules.usedAmount = [{
            required: false,
            message: '请输入用券金额',
            trigger: 'blur'
          }];
          this.addRules.usedAmountDiscount = [{
            required: true,
            message: '请输入折扣,69折输入69',
            trigger: 'blur'
          }]
        }

        this.dialogCouponVisible = true;
      },
      resetForm() {
        this.searchData = {
          totalCount: 0,
          totalPage: 1,
          pageSize: 10
        }
        this.search()
      },
      add() {
        this.dialogCouponVisible = true;
      },
      search() {
        coupons(this.searchData).then(response => {
          if (response.code === 200) {
            this.dataList = response.page.list;
            this.searchData.page = response.page.currPage;
            this.searchData.totalPage = response.page.totalPage;
            this.searchData.totalCount = response.page.totalCount;
          }
        })
      },
      onOpen() {
      },
      onClose() {
        this.$refs['elForm'].resetFields()
      },
      close() {
        this.dialogCouponVisible = false
      },
      handelConfirm() {
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          if (this.addData.usedAmountDiscount !== "") {
            this.addData.usedAmount = this.addData.usedAmountDiscount;
          }
          editCoupon(this.addData).then(response => {
            if (response.code === 200) {
              this.$message({
                showClose: true,
                message: response.msg,
                type: "success"
              });
              this.close()
              this.resetForm()
            } else {
              this.$message({
                showClose: true,
                message: response.msg,
                type: "warning"
              });
            }
          })
        })
      },
      handleAvatarSuccess(res, f) {
        this.addData.icon = res.file;
      },
      beforeAvatarUpload(file) {
        // 关键点注入用户凭证
        this.$refs.upload.headers.Authorization = this.$store.getters.token;
        const isJPG = file.type === "image/jpeg";
        const isPng = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isPng) {
          this.$message.error("上传头像图片只能是 JPG 或 png 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return (isJPG || isPng) && isLt2M;
      },
      //远程请求接口
      remote(data, cb) {
        getProducts(data).then(response => {
          if (response.code === 200) {
            let data = response.page.list;
            data.filter(function (a) {
              a.value = a.productName + "-" + a.productCode + "-" + a.brand;
            });
            cb(data);
          }
        });
      },
      //查询商品名称
      getNameData(queryString, cb) {
        this.remote({productName: queryString}, cb);
      },
      //选择商品
      getChoose(val) {
        this.addData.withSn = val.productCode;
        this.searchData.withSn = val.productCode;
      },
    }
  }

</script>

<style scoped type="scss">

  .el-autocomplete {
    width: 100%;
  }

  .coupon {
    margin-top: 20px;
    .avatar-uploader {
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
          border-color: #409eff;
        }
      }
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 100%;
      display: block;
      max-width: 178px;
    }
    .el-dialog {
      margin-top: 0px !important;
    }
    .el-dialog__body {
      padding-top: 5px !important;
      padding-bottom: 0px !important;
    }
  }

  /*.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }*/
</style>
